<?php
namespace Common\Model;
use Think\Model;

class LinksModel extends  Model{

	public $_validate = array();

	public function addLink(){
		$this->_validate =array(
			array('name','require','链接名称不能为空'),
			array('url','require','链接地址不能为空'),
		);
		if(!$this->create()){
			return false;
		}
		$data = $_POST;
		$res = upload(null,true,'links',null,88,31);
		if($res['code']){
			$data['img'] = $res['path'];
			$this->add($data);
			return true;
		}else{
			$this->error = $res['path'];
			return false;
		}
	}

	public function getList(){
		$p = I('p',0,'int');
		$limit = C('DEFALUT_PAGE_SIZE');
		$startNum = $p > 0 ? ($p - 1) * $limit : 0;
		$count = $this->field("count(*) as count")->find();
		$data = $this->limit($startNum,$limit)->select();
		return array(
			'count' => $count['count'],
			'data'  => $data
		);
	}

	public function editLink(){
		$this->_validate =array(
			array('lname','require','链接名称不能为空'),
			array('lurl','require','链接地址不能为空'),
		);
		if(!$this->create()){
			return false;
		}
		$data = $_POST;
		$data['id'] = I('get.id');
		$key = array_keys($_FILES)[0];
		if($_FILES && $_FILES[$key]['error'] != 4){
			$res = upload(null,true,'links',null,88,31);
			if($res['code']){
				$data['img'] = $res['path'];
			}else{
				$this->error = $res['path'];
				return false;
			}
		}
		$this->save($data);
		return true;
	}

	public function getLinkById($id){
		return $this->find($id);
	}

	public function editLinks(){
		$lid = I('get.lid');
		$this->_validate =array(
			array('name','require','链接名称不能为空'),
			array('url','require','链接地址不能为空'),
		);
		if(!$this->create()){
			return false;
		}
		$data = $_POST;
		//图片上传
		if($_FILES['limg']['error'] != 4  ){
			//上传图像
			$upload = new \Think\Upload();// 实例化上传类
			$upload->maxSize   =     3145728 ;// 设置附件上传大小
			$upload->exts      =     array('jpg', 'gif', 'png', 'jpeg');// 设置附件上传类型
			$upload->savePath  =     'Links/big'; // 设置附件上传目录
			$upload->saveName  =    'duosute_'.date('ymdHis');
			$upload->autoSub   = 	true;
			$upload->callback  =    false;
			$upload->subName   =    false;
			$file =  $upload->upload();
			if(!$file) {// 上传错误提示错误信息
				$this->error='上传错误';
				return false;
			}else{
				$path =  'Uploads/'.$file['limg']['savepath'].$file['limg']['savename'];//原图样式  大图样式
				$thumbPath = 'Uploads/'.$file['limg']['savepath'].'thumb/'.$file['limg']['savename'];
				$thumbPath= str_replace('big/', '', $thumbPath); //组合路径

				$img =  new \Think\Image();
				$img->open($path);
				$img->thumb(88, 31,\Think\Image::IMAGE_THUMB_FIXED)->save($thumbPath);
				$data['limg'] = $file['limg']['savename'];//缩图图
			}
				$this->add($data);
				return true;
		}
		$this->where("lid='{$lid}'")->save($data);
		return true;
	}


	public function getLinks($isshow=1){
		$map['isshow'] = $isshow;
		return $this->where($map)->select();
	}
}
